%% Author: user
%% Created: 2006-8-20
%% Description: TODO: Add desciption to aleph_utility
-module(aleph_utility).
-define(TIMER_TAB, timer_tab). 
%%
%% Include files
%%
    
%%
%% Exported Functions
%%
-export([time_stamp/1,date_to_string/1,
         del_all_of/1,recrusive_dir/1,
         recrusive_dir/2,flat_format/2,
         is_file_exist/1,is_expired/1,
         while/2,is_object/1,int_pow/2]).

%%
%% API Functions
%%
is_expired(Tref={_,_})->
    case ets:lookup(?TIMER_TAB,Tref) of
        []->
            false;
        _->            
            true
     end.
time_stamp(milliseconds)->
    {MegaSecs, Secs, _MicroSecs} =time_stampe(now),
	(MegaSecs * 1000000 + Secs)*1000000+_MicroSecs.
time_stampe(now)->
    now().
date_to_string({{Year,Month,Day},{Hour,Minutes,Second}},Mis)->
    {flat_format("~w-~w-~w", [Year,Month,Day]),
     flat_format("~w:~w:~w-~w",[Hour,Minutes,Second,Mis])}.
date_to_string({MEGA,S,MiS})->
    date_to_string(calendar:now_to_local_time({MEGA,S,MiS}),MiS div 1000).

flat_format(Format,Args)->
    lists:flatten(io_lib:format(Format,Args)).
   
is_file_exist(File_name)->  
        case file:read_file_info(File_name) of
             {ok,_}->true;
             {error,_}->false
        end.
del_all_of(Dir)->
    recrusive_dir(fun(X)->
                   case filelib:is_dir(X) of                      
                       true->file:del_dir(X);
                       false->file:delete(X)end end,Dir).            
                      
recrusive_dir(F,Dir)when is_function(F)==true->    
    lists:foreach(F,recrusive_dir(Dir));
recrusive_dir({error,_},_)->
    [];
recrusive_dir({ok,Sub_dirs},Dir)->
    Width_dirs=lists:foldl(fun(X,Re)->[flat_format("~s\\~s",[Dir,X])|Re]end,[],Sub_dirs),
    Deepth_dirs=lists:foldl(fun(X,Re)->recrusive_dir(file:list_dir(X),X)++Re end,[],Width_dirs),    
    Width_dirs++Deepth_dirs.   
recrusive_dir(Dir)->
    lists:reverse([Dir|recrusive_dir(file:list_dir(Dir),Dir)]). 

while(Fun,Args)->
    case apply(Fun,Args) of
        {_,Ret}->Ret;
        NewArgs->while(Fun,NewArgs)
    end.

is_object(O)->
    is_function(O).       

int_pow(X,Y)->
    round(math:pow(X,Y)).